package com.wifi.eshipewifi;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wifi.BaseApplication;
import com.wifi.imp.MessageListener;
import com.wifi.imp.MessageSend;
import com.wifi.imp.ViewListener;
import com.wifi.utils.Utils;
import com.wifi.utils.WifiUtils;

public class LoginActivity extends BaseActivity implements View.OnClickListener, MessageSend, ViewListener, MessageListener {

    LinearLayout ll_login;
    RelativeLayout rl_main_activity;
    LinearLayout ll_longin_conn;
    TextView tv_login_conn;
    TextView tv_login_pass;
    TextView tv_login_ssid;
    EditText et_login;
    EditText et_password;
    Button bt_login;
    Button login_bt;
    SharedPreferences sp;
    BaseApplication application;
    SocThread thread;
    String TAG = "LoginActivity";
    String login_name;
    String login_pass;
    WifiUtils wifiUtils;
    String connectedSSID;
    String ssid;
    String password;
    String getwayIpS;//网关地址
    String et_login_name;
    String et_login_password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        application = (BaseApplication) getApplication();
        initView();
        wifiUtils = new WifiUtils(LoginActivity.this);
        ssid = application.getSsid();
        password = application.getPassword();
    }

    @Override
    protected int getContentLayoutID() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViewsAndEvents() {

    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        application.setMsgListener(this);
        application.setViewListener(this);
//todo 更改逻辑
        isWifiOpen();
    }

    private void isWifiOpen() {
        //获取系统服务
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取状态
        NetworkInfo.State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        connectedSSID = wifiUtils.getConnectWifiSsid();
        connectedSSID=connectedSSID.replace("\"","");

        //判断wifi已连接的条件
        if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
            ll_longin_conn.setVisibility(View.GONE);
            ll_login.setVisibility(View.VISIBLE);

            boolean b = application.sendMsg("$heartbeat;");
            if(b){//成功连上
                bt_login.setClickable(true);//恢复可点状态
                bt_login.setBackgroundResource(R.drawable.corner_blue_backgound);
            }else {//连接失败
                tv_login_conn.setText("未成功连接正确wifi，请手动连接");
                tv_login_ssid.setText("账号:"+ssid);
                tv_login_pass.setText("密码:"+password);
                ll_longin_conn.setVisibility(View.VISIBLE);
                ll_login.setVisibility(View.GONE);
                application.setNewSocket();
            }
        } else {//wifi未打开
            application.makeToast(LoginActivity.this,"wifi未打开",true);
            tv_login_conn.setText("当前wifi未打开，请手动连接账号");
            tv_login_ssid.setText("账号:"+ssid);
            tv_login_pass.setText("密码:"+password);
            ll_longin_conn.setVisibility(View.VISIBLE);
            ll_login.setVisibility(View.GONE);
        }
    }

    private void initView() {
        rl_main_activity = (RelativeLayout) findViewById(R.id.rl_main_activity);
        rl_main_activity.setBackgroundResource(R.drawable.background);
        ll_login = (LinearLayout) findViewById(R.id.ll_login);
        ll_longin_conn = (LinearLayout) findViewById(R.id.ll_longin_conn);
        tv_login_conn = (TextView) findViewById(R.id.tv_login_conn);//连接wifi按钮
        tv_login_ssid = (TextView) findViewById(R.id.tv_login_ssid);//连接wifi账号
        tv_login_pass = (TextView) findViewById(R.id.tv_login_pass);//连接wifi密码
        login_bt = (Button) findViewById(R.id.login_bt);//连接wifi按钮
        bt_login = (Button) findViewById(R.id.bt_login);
        login_bt.setOnClickListener(this);
        bt_login.setOnClickListener(this);
        et_login = (EditText) findViewById(R.id.et_login);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_login.setOnClickListener(this);
        //等连接成功后才能点击
        bt_login.setBackgroundResource(R.drawable.corner_backgound_gray);
        bt_login.setClickable(false);
        sp = getSharedPreferences("wifiSetting", Activity.MODE_PRIVATE);

        login_name = sp.getString("login_name", "SN000000");
        login_pass = sp.getString("login_pass", "12345678");
        getwayIpS = sp.getString("ip", "192.168.77.1");
        if (login_name != null && login_pass != null) {
            et_login.setText(login_name);
            et_password.setText(login_pass);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_bt://测试
                Intent intent = new Intent();
                intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
//                intent.putExtra("extra_prefs_show_button_bar", true);
                intent.putExtra("extra_prefs_set_next_text", "完成");
                intent.putExtra("extra_prefs_set_back_text", "返回");
//                intent.putExtra("wifi_enable_next_on_connect", true);
                startActivity(intent);
                break;

            case R.id.bt_login:
                et_login_name = et_login.getText().toString().trim();
                et_login_password = et_password.getText().toString().trim();
                if (et_login_name == null) {
                    application.makeToast(LoginActivity.this,"账号不得为空",true);
                } else if (et_login_password == null) {
                    application.makeToast(LoginActivity.this,"密码不得为空",true);
                } else if (et_login_password.length() < 8) {
                    application.makeToast(LoginActivity.this,"密码不得低于八位",true);
                }else {
                    //todo 测试中，具体权限需修改
                    requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionCall() {
                        @Override
                        public void requestSuccess() {
                            application.sendMsg("$login;" + et_login_name + "," + et_login_password + ";");
                            bt_login.setBackgroundResource(R.drawable.corner_backgound_gray);
                            bt_login.setClickable(false);
                        }

                        @Override
                        public void refused() {
                            Toast.makeText(LoginActivity.this, "请授予权限", Toast.LENGTH_LONG).show();
                        }
                    });
                }
                break;
        }
    }

    @Override
    public void SendMessage(String msg) {
        if (msg != null)
            thread.Send(msg);
    }

    @Override
    public void GetNewThread(SocThread thread) {
        this.thread = null;
        this.thread = thread;
    }

    @Override
    public void ViewSetListener() {
       boolean b = application.sendMsg("");
        if(b){//成功连上
            ll_longin_conn.setVisibility(View.GONE);
            ll_login.setVisibility(View.VISIBLE);
            bt_login.setClickable(true);//恢复可点状态
            bt_login.setBackgroundResource(R.drawable.corner_blue_backgound);
        }else {//连接失败
            tv_login_conn.setText("当前wifi未连接正确，请手动连接账号：" + ssid + " 密码：" + password);
            ll_longin_conn.setVisibility(View.VISIBLE);
            ll_login.setVisibility(View.GONE);
        }
    }

    @Override
    public void MessageGetListener(String msg) {
        try {
            if (msg != null) {
                String s = msg;
                if (s.trim().length() > 0) {
                    Log.i(TAG, "MessageGetListener接收到obj=" + s);
                    String s1[] = s.split(";");
                    bt_login.setClickable(true);//恢复可点状态
                    bt_login.setBackgroundResource(R.drawable.corner_blue_backgound);
                    if (s1[1].indexOf("account_password_right") != -1) {//登录成功
                        application.makeToast(LoginActivity.this,"成功登录",true);
                        //保存账号密码
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("login_name", et_login_name);
                        edit.putString("login_pass", et_login_password);
                        edit.putString("ssid", connectedSSID);
                        edit.putString("ip", getwayIpS);
                        application.setIp(getwayIpS);
                        edit.commit();
                        Intent i = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(i);
                        LoginActivity.this.finish();
                    } else if (s1[1].indexOf("account_password_wrong") != -1) {
                        application.makeToast(LoginActivity.this,"账号密码错误！",true);
                    } else if (s1[0].indexOf("first_connect") != -1) {
                        application.makeToast(LoginActivity.this,"连接成功,请稍等",true);
                        application.setIp(getwayIpS);
                    }
                }
            }
            Log.i(TAG, "mhandler接收到msg" + msg);
        } catch (Exception ee) {
            Log.i(TAG, "加载过程出现异常");
            ee.printStackTrace();
        }
    }
}
